from IPy import IP


if __name__ == '__main__':
    # 获取ip范围
    ip_a_file = "D:/桌面/临时文件/0901/ip-a.txt"
    ip_a = []
    with open(file=ip_a_file,encoding='utf-8') as f:
        num = 1
        line = f.readline()
        while (line):
            ips = line[:-2].split("-")
            ip_a.append({"start_ip":ips[0],"end_ip":ips[-1],"num":num})
            line = f.readline()
            num = num + 1
    print(ip_a)
    # 获取去掉的IP
    ip_b = ['41.96.0.1','41.98.31.254','41.97.5.46','41.98.96.2','41.98.191.253']
    # 开始去掉IP，获取最后的范围
    for ip_x in ip_b:
        int_x_IP = IP(ip_x).int()
        for ip_range in ip_a:
            num = ip_range["num"]
            start_ip = ip_range['start_ip']
            end_ip = ip_range['end_ip']
            if (IP(ip_x) > IP(start_ip)) and (IP(ip_x) < IP(end_ip)):
                print(ip_x+"在"+str(ip_range)+"中")
                ip_a.remove(ip_range)
                ip_a.append({"start_ip":start_ip,"end_ip":str(IP(int_x_IP-1)),"num":num})
                ip_a.append({"start_ip":str(IP(int_x_IP+1)),"end_ip":end_ip,"num":num})
            elif ip_x == start_ip:
                print(ip_x+"等于"+str(ip_range)+"的start_ip")
                ip_a.remove(ip_range)
                ip_a.append({"start_ip":str(IP(int_x_IP+1)),"end_ip":end_ip,"num":num})
            elif ip_x == end_ip:
                print(ip_x+"等于"+str(ip_range)+"的end_ip")
                ip_a.remove(ip_range)
                ip_a.append({"start_ip":start_ip,"end_ip":str(IP(int_x_IP-1)),"num":num})
    print(ip_a)
